import { showLoading } from '@tarojs/taro';
import { nextTick, onMounted } from 'vue';
import { QUERY_DOSSIER_LIST } from '/@/api/modules/archive/police/dossier-manager';
import { state } from './state';
import { openArchiveTypeFile } from '/@/utils/file';
import { setCallbackAndDDBackListener } from '/@/utils/back';
export default function useArchiveList() {
  onMounted(() => {
    initArchiveList();
  });

  /**
   * 初始化选中目录
   */
  function initArchiveList() {
    state.selectedTypeList = [];
    state.selectedTypeList.push({
      id: '',
      dossierTypeName: '根目录',
    });
    state.imageList = [];
    state.dossierTypeId = '';
    state.keywords = '';
    refreshList();
    setCallbackAndDDBackListener(condition, queryArchiveByBack);
  }

  /**
   * @description 消息列表查询
   * @param {Number} page -当前页
   * @param {Number} pageSize -每页条数
   */
  function queryList() {
    showLoading();
    QUERY_DOSSIER_LIST({
      dossierTypeId: state.dossierTypeId,
      type: 3,
      flag: 3,
    }).then((res) => {
      res.typeList?.forEach((item) => state.typeList.push(item));
      res.dtoList?.forEach((item) => state.dtoList.push(item));
    });
  }

  /**
   * 刷新列表
   */
  function refreshList() {
    state.typeList = [];
    state.dtoList = [];
    queryList();
  }

  /**
   * 是否是根目录
   */
  function condition() {
    return state.selectedTypeList.length === 1;
  }

  /**
   * 进入子目录
   * @param id 文档id
   */
  function next(item: DossierManager.typeDto) {
    state.dossierTypeId = item.id || '';
    refreshList();
    state.selectedTypeList.push(item);
    scrollViewToRight();
  }

  /**
   * 导航
   * @param index
   */
  function navigation(index: number) {
    //删除的数量
    const count = state.selectedTypeList.length - (index + 1);
    state.selectedTypeList.splice(index + 1, count);
    state.dossierTypeId = state.selectedTypeList[index].id || '';
    refreshList();
  }

  /**
   * scrollView滚动到最右边
   */
  function scrollViewToRight() {
    //子view渲染后才能滚动
    nextTick(() => {
      const dom = document.getElementById('scroll_view_container');
      const scrollWidth = dom?.scrollWidth;
      if (dom && scrollWidth) {
        state.scrollLeft += scrollWidth;
      }
    });
  }

  /**
   *打开文件
   */
  function openFile(item: DossierManager.fileDto) {
    openArchiveTypeFile(item, () => {
      //图片类型
      if (!item.url) {
        return;
      }
      state.imageList = [];
      state.imageList.push(item.url);
      state.showImagePreview = true;
    });
  }

  /**
   * 根据点击back按钮查询档案
   */
  function queryArchiveByBack() {
    state.selectedTypeList.pop();
    //top元素
    const lastedIndex = state.selectedTypeList.length - 1;
    state.dossierTypeId = state.selectedTypeList[lastedIndex].id || '';
    refreshList();
  }

  return { next, navigation, openFile, refreshList };
}
